package problems.daily.y2022m7;

/**
 * @author habitplus
 * @since 2022/7/27 21:14
 **/
public class D20220727_592 {

    public String fractionAddition(String exp) {
        long a = 0, b = 1; // 分子，分母
        int index = 0, n = exp.length();
        while (index < n) {
            // 读取分子
            long a1 = 0, sign = 1;
            if (exp.charAt(index) == '-' || exp.charAt(index) == '+') {
                sign = exp.charAt(index) == '-' ? -1 : 1;
                index++;
            }
            while (index < n && Character.isDigit(exp.charAt(index))) {
                a1 = a1 * 10 + exp.charAt(index) - '0';
                index++;
            }
            a1 = sign * a1;
            // 跳过 '/'
            index++;

            // 读取分母
            long b1 = 0;
            while (index < n && Character.isDigit(exp.charAt(index))) {
                b1 = b1 * 10 + exp.charAt(index) - '0';
                index++;
            }

            a = a * b1 + a1 * b;
            b *= b1;
        }
        if (a == 0) {
            return "0/1";
        }
        long g = gcd(Math.abs(a), b); // 获取最大公约数
        return Long.toString(a / g) + "/" + Long.toString(b / g);
    }

    // 辗转相除法
    public long gcd(long a, long b) {
        long t = a % b;
        while (t != 0) {
            a = b;
            b = t;
            t = a % b;
        }
        return b;
    }
}
